using HY.Common;
using HY.Service;
using HY.Model;
using HY.Web.Models;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Security.Claims;

namespace HY.Web.Controllers
{
    public class BaseController : Controller
    {
        public int RoleId => int.Parse(User?.FindFirstValue(SystemConst.CookieKey.RoleId) ?? "-1");
        public string UserName => User?.FindFirstValue(SystemConst.CookieKey.UserName) ?? string.Empty;

        public ReturnModel returnModel = new() { Code = 200, Count = 0 };

        protected SysLog LogModel { get; set; } = new SysLog() { OpeResult = "成功" };

        public readonly ILogger logger;
        public BaseController(ILogger logger)
        {
            //HttpContext在控制器的构造函数中未初始化，因此无法在此处使用User?.FindFirstValue获取存储的信息
            this.logger = logger;
        }

        /// <summary>
        /// 获取返回值
        /// </summary>
        /// <param name="count"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public ReturnModel Success(int count, object data)
        {
            return new ReturnModel() { Code = 200, Count = count, Message = count > 0 ? "" : "未获取到相应数据", Data = data };
        }

        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="value">对象</param>
        /// <param name="isCamelCase">是否启用驼峰</param>
        /// <returns></returns>
        public string SerializeObject(object value, bool isCamelCase = false)
        {
            var serializerSettings = new JsonSerializerSettings();
            if (isCamelCase)
                serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            return JsonConvert.SerializeObject(value, serializerSettings);
        }

        /// <summary>
        /// 向数据库写入日志
        /// </summary>
        public void LogToDB()
        {
            try
            {
                if (LogModel.UserId == null) LogModel.UserId = int.Parse(User?.FindFirstValue(SystemConst.CookieKey.UserId) ?? "0");
                if (string.IsNullOrWhiteSpace(LogModel.UserName)) LogModel.UserName = User?.FindFirstValue(SystemConst.CookieKey.UserName);
                LogModel.AddTime = DateTime.Now;
                DbContext.SysLog.InsertAsync(LogModel);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, nameof(LogToDB));
            }
        }
    }
}
